<template>
	<div>
		<a-layout>
			<a-layout-content style="background: #fff">
				<a-page-header>
					<template slot="extra">
						<a-button @click="reload()" v-has="'incp.query'">
							<a-icon type="reload" />
						</a-button>
						<a-button
							type="primary"
							@click="addIncpManage"
							v-has="'incp.create'"
						>
							<a-icon type="file-add" />
							添加
						</a-button>
						<a-button type="primary" @click="exportTable">
							<a-icon type="export" />
							导出
						</a-button>
					</template>
					<template slot="title"> {{ $route.meta.title }} </template>
				</a-page-header>

				<a-card :bordered="false">
					<a-form-model layout="inline">
						<a-form-model-item>
							<a-input
								v-model.trim="queryForm.searchkey"
								placeholder="cp名称/用户名"
							>
								<a-icon
									slot="prefix"
									type="copyright"
									style="color: rgba(0, 0, 0, 0.25)"
								/>
							</a-input>
						</a-form-model-item>

						<a-form-model-item>
							<a-select
								allowClear
								v-model.trim="queryForm.market_id"
								style="width: 140px"
								@change="handleMarketChange"
								placeholder="所属市场"
							>
								<a-select-option
									v-for="(item, index) in marketData"
									:key="index"
									:value="item.id"
								>
									{{ item.name }}
								</a-select-option>
							</a-select>
						</a-form-model-item>

						<a-form-model-item>
							<a-button
								v-has="'incp.query'"
								html-type="submit"
								@click="search"
								:disabled="!queryForm.searchkey && !queryForm.market_id"
							>
								查询
							</a-button>
						</a-form-model-item>
						<a-form-model-item>
							<a-button
								v-has="'incp.query'"
								@click="clear"
								:disabled="!queryForm.searchkey && !queryForm.status"
							>
								<a-icon type="delete" />
								清空
							</a-button>
						</a-form-model-item>
					</a-form-model>
				</a-card>

				<div style="margin: 10px 16px 0 16px">
					<a-table
						:columns="columns"
						:data-source="data"
						@change="handleTableChange"
						:loading="loading"
						:pagination="pagination"
						:rowKey="
							(record, index) => {
								return index
							}
						"
					>
						<!-- 自定义表头内容 -->

						<!-- 自定义单元格列的内容 -->
						<template v-slot:name="{ name }">
							<a-tooltip :title="name" placement="topLeft">
								{{ name }}
							</a-tooltip>
						</template>

						<template v-slot:admin_user="{ admin_user }">
							<a-tooltip :title="admin_user" placement="topLeft">
								{{ admin_user }}
							</a-tooltip>
						</template>

						<template v-slot:market_name_show="{ market_name_show }">
							<a-tooltip :title="market_name_show" placement="topLeft">
								{{ market_name_show }}
							</a-tooltip>
						</template>

						<template v-slot:created_at="{ created_at }">
							<a-tooltip :title="formatDate(created_at)" placement="topLeft">
								{{ formatDate(created_at) }}
							</a-tooltip>
						</template>

						<template v-slot:updated_at="{ updated_at }">
							<a-tooltip :title="formatDate(updated_at)" placement="topLeft">
								{{ formatDate(updated_at) }}
							</a-tooltip>
						</template>

						<template v-slot:map_area_list="{ map_area_list }">
							<a-tooltip :title="arrToStr(map_area_list)" placement="topLeft">
								{{ arrToStr(map_area_list) }}
							</a-tooltip>
						</template>

						<span slot="status" slot-scope="text" style="white-space: nowrap">
							<template>
								<a-badge
									:status="statusTypeFilter(text)"
									:text="statusFilter(text)"
								/>
							</template>
						</span>
						<span slot="action" slot-scope="text, record">
							<template>
								<a @click="setIncpAdmin(record)" v-has="'incpuser.create'"
									>设置CP管理员</a
								>
								<!-- <a @click="setIncpAdmin(record)" v-has="'incpuser.update'"
									>设置CP管理员</a
								> -->

								<a-divider type="vertical" />
								<!-- <a @click="incpUserList(record)">CP用户列表</a>
								<a-divider type="vertical" /> -->
								<a @click="deleteIncp(record)" v-has="'incp.delete'">删除</a>
								<a-divider type="vertical" />
								<a @click="updateIncp(record)" v-has="'incp.update'">修改</a>
							</template>
						</span>
					</a-table>
				</div>
			</a-layout-content>
		</a-layout>
		<handle-table
			ref="handleTable"
			@handleOk="handleTableChange"
		></handle-table>
		<!-- 设置场内CP管理员 -->
		<handleManageForm ref="handleManageForm" @handleOk="handleTableChange" />
		<!-- 场内CP用户列表 -->
		<!-- <cpuserTableList @handleTableStatus="handleTableStatus" v-if="!flag" /> -->
	</div>
</template>

<script>
	const tableObj = require("./json/table.json")
	import Incp from "@/api/incp"
	import momentUtil from "@/utils/day"
	import handleTable from "./components/handleForm.vue"
	import handleManageForm from "./components/handleManageForm.vue"
	// import cpuserTableList from "./components/cpuserTableList.vue"
	import salemarket from "@/api/salemarket"
	export default {
		data() {
			this.statusMap = {
				1: {
					status: "success",
					text: "正常",
				},
				0: {
					status: "default",
					text: "停用",
				},
				"-1": {
					status: "error",
					text: "冻结",
				},
			}
			return {
				// flag: true,
				marketData: [],
				queryForm: {
					market_id: undefined,
					searchkey: "",
					status: undefined, //placeholder 生效
				},
				data: [],
				columns: tableObj.columns,
				loading: false,
				pagination: {
					current: 1,
					pageSize: 20,
					total: 0,
					totalPage: 0,
					showSizeChanger: true,
					showTotal: (total) => `总 ${total} 条`,
				},
			}
		},

		filters: {
			formatStamp(stamp) {
				console.log(momentUtil.timestamp2Day(stamp, "YYYY-MM-DD hh:mm:ss"))
				return momentUtil.timestamp2Day(stamp, "YYYY-MM-DD hh:mm:ss")
			},
		},
		created() {
			this.getData()
			// 获取批发市场列表
			this.getMarketList()
		},
		methods: {
			reload() {
				window.location.reload()
			},
			// handleTableStatus() {
			// 	this.flag = true
			// },
			// incpUserList() {
			// 	this.flag = false
			// },
			// 设置CP管理员
			setIncpAdmin(record) {
				this.$refs.handleManageForm.showModal("set", record)
			},
			// calcTableWidth(columns) {
			// 	let totalWidth = 0
			// 	for (let i = 0, len = columns.length; i < len; i++) {
			// 		if (columns[i].width) {
			// 			totalWidth += columns[i].width
			// 		} else {
			// 			totalWidth += 120
			// 		}
			// 	}
			// 	return totalWidth
			// },
			async getMarketList(params = {}) {
				// this.resetFormFields()
				this.marketData = []

				await salemarket.query(params).then((response) => {
					console.log("市场列表数据", response)
					if (response.code !== 1) {
						this.$message.warning(response.message)
						return
					}

					if (response.data && response.data.length > 0) {
						this.marketData = response.data.map((item) => {
							return {
								id: item.id,
								name: item.name,
							}
						})
					}
				})
			},
			handleMarketChange(market_id) {
				this.queryForm.market_id = market_id
				this.getData()
				// console.log(`selected ${market_id}`)
				// this.areaList = []
				// this.form.map_area_id = undefined
				// this.getAreaList(market_id)
			},
			arrToStr(map_area_list) {
				if (!map_area_list) return
				if (map_area_list && map_area_list.length > 0) {
					return map_area_list
						.map((item) => {
							return item.name
						})
						.join("\r\n")
				} else {
					return ""
				}
			},
			formatDate(timeStr) {
				if (["", "undefined", "null", "NaN", "false"].includes(timeStr + ""))
					return
				// console.log(timeStr)
				if (!timeStr) return
				// console.log(
				// 	+new Date(timeStr),
				// 	this.$formatDate("Y-M-D h:m:s", +new Date(timeStr))
				// )
				return this.$formatDate("Y-M-D h:m:s", +new Date(timeStr))
			},

			deleteIncp(record) {
				console.log(record)
				this.$modal.confirm({
					title: "提示",
					content: "是否删除？",
					okText: "确定",
					cancelText: "取消",
					centered: true,
					onOk: () => {
						console.log("删除")

						Incp.delete(record.id).then((response) => {
							if (response.code !== 1) {
								this.$message.error(response.message)
								return
							}
							this.$message.success(response.message)
							// this.queryForm()
							this.getData()
							return
						})
					},
					onCancel: () => {
						this.$message.warning("删除取消了")
					},
				})
			},
			updateIncp(item) {
				// console.log(item)
				// console.log(this.$refs.handleTable)
				this.$refs.handleTable.showModal("update", item)
			},
			handleTableChange(pagination, filters, sorter) {
				console.table({
					pagination,
					filters,
					sorter,
				})
				if (sorter) {
					if (sorter.order) {
						Object.assign(this.queryForm, {
							order_by: `${sorter.columnKey} ${sorter.order.slice(0, -3)}`,
						})
					} else {
						delete this.queryForm.order_by
					}
				}
				this.pagination = pagination || this.pagination
				this.getData()
			},
			getData() {
				this.loading = true
				let pageMap = {
					page: this.pagination.current,
					pageSize: this.pagination.pageSize,
				}
				Incp.query(Object.assign(pageMap, this.queryForm))
					.then((res) => {
						console.log("场内CP管理", res)
						this.loading = false
						if (res.code == 1) {
							this.pagination.total = res.page.totalSize
							this.pagination.totalPage = res.page.totalPage
							//dataSource 默认将每列数据的 key 属性作为唯一的标识
							//处理数据，否则需要excel代码里处理了
							// this.data = res.data.map((item, index) => {
							// 	return Object.assign(item, { index: index + 1 })
							// })
							this.data = res.data
							// ========================
							// if (this.data.length === 0) {
							// 	this.data = [
							// 		{ id: "1", name: "a" },
							// 		{ id: "2", name: "b" },
							// 	]
							// }
							// ========================
							console.log(this.data)
						}
					})
					.catch((e) => {
						this.data = []
						this.pagination.total = 0
						this.pagination.totalPage = 1
						this.loading = false
					})
			},
			exportTable() {
				this.$excelUtil.genTable({
					excelName: `${this.$route.meta.title}`,
					columns: tableObj.columns,
					tableData: this.handleData(this.data),
					filterKeys: ["action"],
				})
			},
			//解析数据中不能识别部分
			handleData(data) {
				return data.map((item) => {
					return Object.assign({}, item, {
						status: this.statusMap[item.status + ""].text,
						created_at: this.formatDate(item.created_at),
						updated_at: this.formatDate(item.updated_at),
					})
				})
			},
			addIncpManage() {
				this.$refs.handleTable.showModal("add")
				// this.$refs.handleManageForm.showModal("add", "添加场内CP管理员")
			},
			statusFilter(status) {
				// console.log(status)

				if (["", "undefined", "null", "NaN", "false"].includes(status + ""))
					return

				return this.statusMap[status + ""]
					? this.statusMap[status + ""].text
					: undefined
			},
			statusTypeFilter(status) {
				// console.log(status)
				if (["", "undefined", "null", "NaN", "false"].includes(status + ""))
					return
				return this.statusMap[status + ""]
					? this.statusMap[status + ""].status
					: undefined
			},
			search() {
				this.data = []
				this.pagination.current = 1
				this.getData()
			},
			clear() {
				this.queryForm.searchkey = ""
				this.queryForm.status = undefined
				this.getData()
			},
		},
		components: {
			handleTable,
			handleManageForm,
			// cpuserTableList,
			// detailPage,
		},
	}
</script>

<style lang="less" type="text/less" scoped></style>